package com.appbee.core.client.modular.impl;

import java.util.HashMap;

import com.appbee.core.client.modular.IModul;
import com.appbee.core.client.modular.INavItem;
import com.appbee.core.client.modular.SettingsView;
import com.appbee.core.client.place.INamePlace;
import com.google.gwt.activity.shared.Activity;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.user.client.rpc.AsyncCallback;

public abstract class ActivityModul implements IModul
{
	protected INavItem currentNavItem;
	private final HashMap<String, AsyncProvider<? extends Activity>> registry = new HashMap<String, AsyncProvider<? extends Activity>>();
	private AsyncProvider<? extends Activity> defaultActivty;

	@Override
	public void getActivity(INamePlace place, AsyncCallback<Activity> callback)
	{
		String path = currentNavItem == null ? "" : currentNavItem.getPath();
		if (path == null)
			path = "";
		String placeName = place == null ? "" : place.getName();

		@SuppressWarnings("unchecked")
		AsyncProvider<Activity> activtyProvider = (AsyncProvider<Activity>) defaultActivty;
		// Return defaultActivity if place has no subpath.
		if (placeName.length() > path.length())
		{
			// Get subpath
			String activityId = placeName.substring(path.length() + 1);

			// Return default activity if not found
			@SuppressWarnings("unchecked")
			AsyncProvider<Activity> subAactivityProvider = (AsyncProvider<Activity>) registry
					.get(activityId);
			if (subAactivityProvider != null)
				activtyProvider = subAactivityProvider;
		}
		activtyProvider.get(callback);

	}

	@Override
	public void setCurrentNavItem(INavItem navItem)
	{
		this.currentNavItem = navItem;
	}

	public AsyncProvider<? extends Activity> getDefaultActivty()
	{
		return defaultActivty;
	}

	public void setDefaultActivty(AsyncProvider<? extends Activity> defaultActivty)
	{
		this.defaultActivty = defaultActivty;
	}

	public void register(String id, AsyncProvider<? extends Activity> activity)
	{
		registry.put(id, activity);
	}

	@Override
	public void getSettingsView(final AsyncCallback<SettingsView> callback)
	{
		callback.onSuccess(null);
	}

}
